package com.tang.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.reggie.common.R;
import com.tang.reggie.mapper.EmployeeMapper;
import com.tang.reggie.pojo.Employee;
import com.tang.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 登录
     * @param employee
     * @return
     */
    @Override
    public R login(Employee employee) {
        //查询数据库中有没有该用户名
        String username = employee.getUsername();
        if (username!=null&&username!=""){
            username=username.trim();
        }
        log.info("username={}",username);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotEmpty(username),Employee::getUsername,username);
        Employee emp = getOne(lqw);//根据唯一的条件查询出指定数据
        if (emp==null){
            return R.error(username+":用户不存在");
        }
        //密码验证
        String password = employee.getPassword();
        password= DigestUtils.md5DigestAsHex(password.getBytes());
        if (!emp.getPassword().equals(password)){
            return R.error("用户名密码不一致");
        }
        //状态验证
        if (emp.getStatus()==0){
            return R.error("该用户已禁用");
        }
        return R.success(emp);
    }

    /**
     * 添加
     * @param employee
     */
    @Override
    public boolean addEmployee(Employee employee) {
        //设置默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //去掉用户名的前后空格
        String username = employee.getUsername().trim();
        employee.setUsername(username);

        //执行mapper添加方法
        int i = employeeMapper.insert(employee);
        if (i>0){
            return true;
        }
        return false;
    }

    /**
     * 查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<Employee> find(int page, int pageSize, String name) {
        //分页
        Page<Employee> pageInfo = new Page<Employee>(page, pageSize);
        //条件
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //判断是否不为null且不为空
        if (StringUtils.isNotBlank(name)){
            name=name.trim();
            lqw.like(Employee::getName,name);
        }
        //排序条件
        lqw.orderByDesc(Employee::getUpdateTime);
        page(pageInfo, lqw);
        return pageInfo;
    }
}
